package com.example.lib_base.net

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData

class LiveDataBus {
    //伴生对象 实例化liveDataBus
    companion object{
        val instance:LiveDataBus by lazy { LiveDataBus() }
    }
    //定义一个map集合用来接收数据
    private val liveDataMap = hashMapOf<String,MutableLiveData<Any>>()
    //定义一个发送事件的方法 （点击事件时调用）
    fun <T> sendEvent(key:String,value: T){
        //判断是否存在
        if(!liveDataMap.containsKey(key)){
            liveDataMap[key] = MutableLiveData()
        }
        (liveDataMap[key] as MutableLiveData<T>).postValue(value)
    }
    //接收事件 （响应点击事件时调用）
    fun <T> getEvent(key: String):LiveData<T>{
        //判断是否存在
        if(!liveDataMap.containsKey(key)){
            liveDataMap[key] = MutableLiveData()
        }
        return liveDataMap[key] as LiveData<T>
    }
}